package chapter12.section3;

/*程序12-5：客户端程序，模拟银行用户向服务器发送业务请求。*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class EBankClient2 {
	public static void main(String[] args) {
		String[] types = { "deposit", "withdraw", "query", "bye" };
		Socket client = null;
		try {
			client = new Socket("127.0.0.1", 7788);
			BufferedReader in = null;
			PrintWriter out = null;
			out = new PrintWriter(client.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			String req = null;
			String resp = null;
			Scanner sc = new Scanner(System.in);
			boolean working = true;
			while (working) {
				System.out.println("输入您的账户id：");
				String id = sc.next();
				System.out.println("选择本次业务类型[0:存款,1:取款,2：查询,3：退出]：");
				int type = sc.nextInt();
				int amount = 0;
				if (types[type].equals("bye")) {
					working = false;
//为了保持服务器解析正确,依然需要按格式发送
					req = types[type] + "," + id + ",0";
				} else if (types[type].equals("query")) {
					// 为了保持服务器解析正确,依然需要按格式发送
					req = types[type] + "," + id + ",0";
				} else {
					System.out.println("输入交易金额：");
					amount = sc.nextInt();
					// 构造一个符合服务器解析格式要求的请求字符串
					req = types[type] + "," + id + "," + amount;
				}
				// 将请求信息提交到服务器
				out.println(req);
				if (working) {
					// 接受服务器的响应
					resp = in.readLine();
					System.out.println("response:" + resp);
				}
			}
			client.close();
		} catch (UnknownHostException e) {
			System.out.println("指定的服务器地址错误");
			System.exit(-1);
		} catch (IOException e) {
			System.out.println("创建和服务器的连接时发生错误");
			System.exit(-1);
		}
	}
}